package main

import (
	"context"
	"fmt"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/hertz-contrib/etag"
	httpcache "github.com/hertz-contrib/httpcache/server"
	"github.com/hertz-contrib/opensergo/sentinel/adapter"
	"hertz-nbdemo/biz/dal"
	"hertz-nbdemo/pkg/logger"
	"hertz-nbdemo/pkg/redis"
)

func Init() {
	logger.InitLogger()
	dal.InitDal()
	redis.InitRedisClient()
}

func main() {
	Init()
	h := server.Default(
		server.WithHostPorts("0.0.0.0:8080"),
	)
	// store := cookie.NewStore([]byte("secret"))
	// h.Use(sessions.New("session", store))
	// h.Use(csrf.New(
	//	csrf.WithSecret("secret123"),
	//	csrf.WithErrorFunc(func(c context.Context, ctx *app.RequestContext) {
	//		ctx.String(400, ctx.Errors.Last().Error())
	//		ctx.Abort()
	//	},
	//	)))
	// h.Use(limiter.AdaptiveLimit())
	h.Use(adapter.SentinelServerMiddleware(
		adapter.WithServerResourceExtractor(func(c context.Context, ctx *app.RequestContext) string {
			return fmt.Sprintf("%v:%v", string(ctx.Request.Method()), string(ctx.Request.Path()))
		}),
		adapter.WithServerBlockFallback(func(c context.Context, ctx *app.RequestContext) {
			ctx.AbortWithStatusJSON(400, utils.H{
				"err":  "too many request; the quota used up",
				"code": 10222,
			})
		}),
	))
	h.Use(etag.New())
	h.Use(httpcache.NewHTTPCache(httpcache.DevDefaultConfiguration))
	v1 := h.Group("/v1")
	registerV1(v1)
	h.Spin()
}
